//注册登录接口
const router = require('koa-router')()
const result = require('../../config/result')
const {getToken,addUrl,whereUrl} = require('../../config/databaseapi')
const {regCheck} = require('../../config/checking')
const {creatToken} = require('../../token/jwt')
const {Auth} = require('../../token/auth')
//注册接口
router.post('/register',async ctx =>{
    let {account,password} = ctx.request.body
    new regCheck(ctx,account,password).start()
    //查询手机是否注册过
    const query = `db.collection('business-acc').where({account:'${account}'}).get()`
    try {
        const user = await new getToken().posteve(whereUrl,query)
        if (user.data.length > 0) {
            //已经注册过
            new result(ctx,'已经注册过手机号',202).answer()
        }else{
            //没有注册过，获取唯一uid
            const uid = new Date().getTime()
            const struid = JSON.stringify(uid) 
            const OBJ = {
                account,
                password,
                uid : struid
            }
            const STR = JSON.stringify(OBJ)
            const addQuery = `db.collection('business-acc').add({data:${STR}})`
            const res = await new getToken().posteve(addUrl,addQuery)
            new result(ctx,'注册成功',200).answer()
        }
    } catch (error) {
        new result(ctx,'注册失败',500).answer()
        
    }
})
//登录接口
router.post('/login',async ctx => {
    let {account,password} = ctx.request.body
    const query = `db.collection('business-acc').where({account:'${account}',password:'${password}'}).get()`
    try {
        const user = await new getToken().posteve(whereUrl,query)
        if (user.data.length == 0) {
            new result(ctx,'账号或密码错误',202).answer()
        }else{
            const OBJ = JSON.parse(user.data[0])
            new result(ctx,'登陆成功',200,{token:creatToken(OBJ.uid)}).answer()
        }
    } catch (error) {
        new result(ctx,'注册失败',500).answer()
        
    }
})
//验证token
router.get('/yanzheng',new Auth().m,async ctx =>{
    console.log(ctx.auth.uid);
})
module.exports = router.routes()